package com.ds.yuntukubackend.manager.upload;

import cn.hutool.core.io.FileUtil;
import com.ds.yuntukubackend.exception.ErrorCode;
import com.ds.yuntukubackend.exception.ThrowUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.Arrays;
import java.util.List;

/**
 * 文件图片上传
 */
@Service
public class FilePictureUpload extends PictureUploadTemplate {
    /**
     * 校验文件
     * @param inputSource
     */
    @Override
    protected void validPicture(Object inputSource) {
        MultipartFile multipartFile = (MultipartFile)inputSource;
        ThrowUtils.throwIf(multipartFile==null, ErrorCode.PARAMS_ERROR,"文件不能为空");
        //1.校验文件大小
        long fileSize = multipartFile.getSize();
        final long ONE_M = 1024 * 1024;
        ThrowUtils.throwIf(fileSize > 10 * ONE_M, ErrorCode.PARAMS_ERROR,"文件大小不能超过10M" );
        //2.校验文件后缀
        String fileSuffix = FileUtil.getSuffix(multipartFile.getOriginalFilename());
        //允许上传的文件后缀
        final List<String> ALLOWED_SUFFIX = Arrays.asList("png", "jpg", "jpeg", "gif");
        ThrowUtils.throwIf(!ALLOWED_SUFFIX.contains(fileSuffix),ErrorCode.PARAMS_ERROR,"文件格式不合法" );

    }

    /**
     * 获取输入源的原始文件名称
     *
     * @param inputSource
     * @return
     */
    @Override
    protected String getOriginFilename(Object inputSource) {
        MultipartFile multipartFile = (MultipartFile)inputSource;
        return multipartFile.getOriginalFilename();
    }

    /**
     * 处理输入源并生成本地临时文件
     *
     * @param inputSource
     * @param file
     */
    @Override
    protected void processFile(Object inputSource, File file) throws Exception {
        MultipartFile multipartFile = (MultipartFile)inputSource;
        multipartFile.transferTo(file);
    }
}
